<?php

declare(strict_types=1);

namespace App\Common\Event;

use Hyperf\Database\Events\QueryExecuted;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Collection\Arr;
use Hyperf\Stringable\Str;
use Psr\Log\LoggerInterface;
use function Hyperf\Config\config;

#[Listener]
class SqlListener implements ListenerInterface
{
    protected LoggerInterface $logger;


    public function __construct()
    {
        $this->logger = logger('sql', 'sql');
    }

    public function listen(): array
    {
        $listen = [];
        if (config('app.record_sql')) {
            $listen[] = QueryExecuted::class;//判断是否记录sql
        }
        return $listen;
    }

    /**
     * @param object $event
     */
    public function process(object $event): void
    {
        if ($event instanceof QueryExecuted) {
            $sql = $event->sql;
            if (!Arr::isAssoc($event->bindings)) {
                foreach ($event->bindings as $value) {
                    $sql = Str::replaceFirst('?', "'{$value}'", $sql);
                }
            }
            $this->logger->info($sql);
        }
    }
}
